package com.wxit.algorithm.practice;

/**
 * 杨辉三角
 */
public class PascalTriangle {
    public static void main(String[] args) {
       print2(5);
    }

    public static void print2(int n) {
        int[] row = new int[n];
        for (int i = 0; i < n; i++) {
            // 打印空格
            createRow(row, i);
            for (int j = 0; j <= i; j++) {
                System.out.printf("%-4d", row[j]);
            }
            System.out.println();
        }
    }

    private static void createRow(int[] row, int i) {
        if (i == 0) {
            row[0] = 1;
            return;
        }
        for (int j = i; j > 0; j--) {
            row[j] = row[j - 1] + row[j];
        }
    }

    public static void print1(int n) {
        int[][] triangle = new int[n][];
        for (int i = 0; i < n; i++) {
            printSpace(n, i);
            triangle[i] = new int[i + 1];
            for (int j = 0; j <= i; j++) {
                System.out.printf("%-4d", element(i, j));
            }
            System.out.println();
        }
    }


    /**
     * 使用二维数组进行优化
     * @param triangle
     * @param i
     * @param j
     * @return
     */
    public static int element1(int[][] triangle, int i, int j) {
       if (triangle[i][j] > 0) {
           return triangle[i][j];
       }
       if (j == 0 || i == j) {
           triangle[i][j] = 1;
           return triangle[i][j];
       }
       triangle[i][j] = element1(triangle, i - 1, j - 1) + element1(triangle, i - 1, j);
       return triangle[i][j];
    }



    private static void printSpace(int n, int i) {
        int num = (n - 1 - i) * 2;
        for (int j = 0; j < num; j++) {
            System.out.print(" ");
        }
    }

    public static void print(int n) {
        for (int i = 0; i < n; i++) {
            printSpace(n, i);
            for (int j = 0; j <= i; j++) {
                System.out.printf("%-4d", element(i, j));
            }
            System.out.println();
        }
    }

    private static int element(int i, int j) {
        if (j == 0 || i == j) {
            return 1;
        }
        return element(i - 1, j) + element(i - 1, j - 1);
    }
}
